package com.example.lib.muchthread;

/**
 * 如果同步函数被静态修饰后，使用的锁是什么呢？
 * 通过验证，发现不再是this.因为静态方法中也不可以定义this.
 *
 * 静态进内存时，内存中没有本类对象，但是一定有该类对应的字节码文件对象。
 * 类名.class  该对象的类型是Class
 *
 * 静态的同步方法，使用的锁是该方法所在类的字节码文件对象.类名.class
 */

public class j_static_sync_method_139 {
    public static void main(String[] args) {
        Ticket139 runnable = new Ticket139();

        Thread t1 = new Thread(runnable);
        Thread t2 = new Thread(runnable);

        t1.start();
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        runnable.flag = false;
        t2.start();
    }
}

class Ticket139 implements Runnable {

    private static int tick = 100;
    boolean flag = true;

    @Override
    public void run() {

        if (flag) {
            while (true) {
                synchronized (Ticket139.class) {
                    if (tick > 0) {
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        System.out.println(Thread.currentThread().getName() + "...同步代码块:" + tick--);
                    }
                }
            }
        } else {
            while (true) {
                show();
            }
        }
    }

    public static synchronized void show() {
        if (tick > 0) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + "......同步函数:" + tick--);
        }
    }
}
